<?php
/**
 * OAuthApiForQQ class file.
 *
 * @author Zhang Jinlong <466028373@qq.com>
 * @link http://www.ijianzhi.cn
 * @copyright Copyright &copy; 2013 DianJin Soft
 */

class OAuthApiForQQ
{
    /**
     * ACCESS TOKEN
     * @var string
     */
    public $accessToken;

    /**
     * OPEN-ID
     * @var string
     */
    public $openId;

    /**
     * API 配置
     * @var array
     */
    public $apiMap;

    /**
     * 构造函数
     */
    public function __construct($accessToken = NULL, $openId = NULL)
    {
        $this->accessToken = !is_null($accessToken) ? $accessToken : Yii::app()->session['qq_access_token'];
        $this->openId = !is_null($openId) ? $openId : Yii::app()->session['qq_openid'];

        /**
         * API配置
         * @var unknown_type
         */
        $this->apiMap = array(
            'getUserInfo' => array(
                'url' => Yii::app()->params['oauth']['qq']['getUserInfoUrl'],
                'data' => array('format' => 'json'),
                'method' => 'POST',
            ),

            'addShare' => array(
                'url' => Yii::app()->params['oauth']['qq']['addShareUrl'],
                'data' => array('format' => 'json'),
                'method' => 'POST',
            ),
        );
    }

    /**
     * 调取各个API的魔术方法
     * @param string $name
     * @param array $args
     */
    public function __call($name, $args)
    {
        $config = $this->apiMap[$name];

        $data = isset($args[0]) ? $args[0] : array();
        $data = array_merge($config['data'], $data);

        $data['oauth_consumer_key'] = Yii::app()->params['oauth']['qq']['appId'];
        $data['access_token'] = $this->accessToken;
        $data['openid'] = $this->openId;

        if ($config['method'] === 'POST')
        {
            $response = WebHelper::post($config['url'], $data);
        }
        else
        {
            $url = $config['url'].'?'.http_build_query($data);
            $response = WebHelper::get($url);
        }

        $response = json_decode($response, TRUE);

        /* API调取失败 */
        if ($response['ret'] !== Constants::QQ_API_SUCCEED)
        {
            throw new OAuthException("Call the api \"{$name}\" fail with message: {$response['msg']}", $response['ret']);
        }

        return $response;
    }
}